/** @file    ClientHttp.cpp
 *  @author  Alessandro Polo
 *  @version $Id: ClientHttp.cpp 2821 2010-08-01 11:44:26Z alex $
 *  @brief
 * File containing methods for the wosh::network::ClientHttp class.
 * The header for this class can be found in ClientHttp.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/
 
 #include <framework/network/ClientHttp.h>

// #include <framework/network/NetworkUtilities.h>
 #include <core/Utilities.h>

 #include <QFile>
 #include <QFileInfo>
 #include <QUrl>
 #include <QtNetwork/QHttp>


using namespace std;
namespace wosh {
 namespace network {

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS

ClientHttp::ClientHttp()
	: QObject() {
	this->listener = NULL;

	Log.setContext( "ClientHttp" );
	Log.setLevel( LOG_INFO );
	Log.setIndent( 5 );
Log.setLevel( LOG_VERBOSE );

	this->httpFile = NULL;
	this->httpSocket = new QHttp(this);

	connect(this->httpSocket, SIGNAL(requestStarted(int)),this, SLOT(httpRequestStarted(int)));
	connect(this->httpSocket, SIGNAL(requestFinished(int, bool)),this, SLOT(httpRequestFinished(int, bool)));
	connect(this->httpSocket, SIGNAL(dataReadProgress(int, int)),this, SLOT(updateDataReadProgress(int, int)));
	connect(this->httpSocket, SIGNAL(responseHeaderReceived(const QHttpResponseHeader &)),this, SLOT(readResponseHeader(const QHttpResponseHeader &)));
	connect(this->httpSocket, SIGNAL(done(bool)),this, SLOT(done(bool)));
 }

ClientHttp::~ClientHttp() {
	Log(LOG_VERBOSE, ":~ClientHttp() Dstroying.." );

	if ( this->httpSocket != NULL )
		delete this->httpSocket; this->httpSocket = NULL;

	if ( this->httpFile != NULL )
		delete this->httpFile; this->httpFile = NULL;
 }

//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ClientHttp::readResponseHeader( const QHttpResponseHeader &responseHeader ){
	if ( responseHeader.statusCode() == 200 ) {
		Log(LOG_VERBOSE, ":readResponseHeader() : Succeeded (%d)", responseHeader.statusCode() );
		return;
	 }
	Log(LOG_CRITICAL, ":readResponseHeader() : FAILED Status Code %d [%s]", responseHeader.statusCode(), responseHeader.reasonPhrase().toLatin1().data() );
	this->httpRequestAborted = true;
	this->httpSocket->abort();
	return;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ClientHttp::updateDataReadProgress( int bytesRead, int totalBytes ) {
	Log(LOG_VERBOSE, ":updateDataReadProgress(%d,%d) %f percent", bytesRead, totalBytes, (float)(totalBytes/bytesRead)*100.0 );
	if ( this->listener == NULL )
		return;
	this->listener->httpDataReadProgress( bytesRead, totalBytes, this );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void ClientHttp::done( bool error ) {
	if ( error ) {
		Log(LOG_CRITICAL, ":done()" );
		return;
	 }
	Log(LOG_VERBOSE, ":done()" );
 }

void ClientHttp::httpRequestStarted( int requestId ) {
	Log(LOG_VERBOSE, ":httpRequestStarted(%d)", requestId );
 }

void ClientHttp::httpRequestFinished( int requestId, bool error ) {
	if ( this->httpRequestAborted ) {
		if ( this->httpFile ) {
			Log(LOG_VERBOSE, ":httpRequestFinished(%d,%d) : Aborted [closing file]", requestId, (int)error );
			this->httpFile->close();
			this->httpFile->remove();
			delete this->httpFile; this->httpFile = NULL;
		 }
		else
			Log(LOG_VERBOSE, ":httpRequestFinished(%d,%d) : Aborted", requestId, (int)error );
		return;
	 }
	if ( requestId != this->httpGetId )
		return;

	this->httpFile->close();

	if ( error ) {
		Log(LOG_CRITICAL, ":httpRequestFinished(%d) : Download Failed [%s]!", requestId, this->httpSocket->errorString().toLatin1().data() );
		this->httpFile->remove();
		if ( this->listener == NULL )
			return;
		this->listener->httpRequestError(this);
		return;
	 }
	Log(LOG_INFO, ":httpRequestFinished(%d,%d) : Succeeded!", requestId, (int)error );

	delete this->httpFile; this->httpFile = NULL;
	if ( this->listener == NULL )
		return;
	this->listener->httpRequestCompleted(this);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT ClientHttp::downloadFile( const wosh::ResourcePath& value, const wosh::FilePath& localPath ) {
	WRESULT urlSet = setHttpUrl( value );
	if ( WFAILED(urlSet) ) {
		return WRET_ERR_PARAM;
	 }
	WRESULT pathSet = setTargetPath( localPath );
	if ( WFAILED(pathSet) ) {
		return WRET_ERR_PARAM;
	 }
	Log(LOG_VERBOSE, ":downloadFile(%s)", value.getPathFull().c_str() );
	return downloadFile();
 }

WRESULT ClientHttp::downloadFile() {
	QUrl url( this->httpUrl.getPathFull().c_str() );
	QString filePath = this->targetPath.toPathLocal().c_str();
	Log(LOG_VERBOSE, ":downloadFile() %s to %s", this->httpUrl.getPathFull().c_str(), filePath.toLatin1().data() );

	if ( QFile::exists(filePath) ) {
		Log(LOG_WARNING, ":downloadFile() Local file Exists: %s [overwriting]", filePath.toLatin1().data() );
	 }
	this->httpFile = new QFile( filePath );
	if ( !this->httpFile->open(QIODevice::WriteOnly) ) {
		Log(LOG_CRITICAL, ":downloadFile() Write Error: %s", filePath.toLatin1().data() );
		delete this->httpFile; this->httpFile = NULL;
		return WRET_ERR_INTERNAL;
	}
	this->httpSocket->setHost( url.host(), url.port() != -1 ? url.port() : 80 );
	if ( !this->httpUsername.empty() ) {
		this->httpSocket->setUser( this->httpUsername.c_str(), this->httpPassword.c_str() );
	 }
	this->httpRequestAborted = false;
	this->httpGetId = this->httpSocket->get(this->httpUrl.getPathFull().c_str(), this->httpFile);
	Log(LOG_VERBOSE, ":downloadFile() Initializing Request.. [%d]", this->httpGetId );
	if ( this->listener != NULL )
		this->listener->httpRequestInitiated(this);
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT ClientHttp::cancelDownload() {
	if ( this->httpRequestAborted ) {
		Log(LOG_WARNING, ":cancelDownload() : Already issued!" );
		return WRET_ERR_ILLEGAL_USE;
	 }
	Log(LOG_INFO, ":cancelDownload() : AbortRequest raised." );
	this->httpRequestAborted = true;
	this->httpSocket->abort();
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool ClientHttp::isDownloading() const {
	return this->httpSocket->currentId() != 0;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT ClientHttp::setHttpUrl( const wosh::ResourcePath& value, const std::string& username, const std::string& password ) {
	if ( isDownloading() ) {
		Log(LOG_CRITICAL, ":setHttpUrl(%s ,%s) : Already downloading!", value.getPathFull().c_str(), username.c_str() );
		return WRET_ERR_PARAM;
	 }
	this->httpUrl = value;
	this->httpUsername = username;
	this->httpPassword = password;
	Log(LOG_VERBOSE, ":setHttpUrl(%s ,%s)", value.getPathFull().c_str(), username.c_str() );
	return WRET_OK;
 }

WRESULT ClientHttp::setTargetPath( const wosh::FilePath& value ) {
	if ( isDownloading() ) {
		Log(LOG_CRITICAL, ":setHttpUrl(%s ,%s) : Already downloading!", value.getPathFull().c_str() );
		return WRET_ERR_PARAM;
	 }
	this->targetPath = value;
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace network
}; // namespace wosh
